<template>
  <el-dialog :title="$t('personal.updateRole.title')" :visible.sync="showUpdateDialog" width="400px" @close="reset">
    <div class="base-modal-content">
      <!-- 内容主体区域 -->
      <el-select v-model="roleIds" :placeholder="$t('common.placeholder.selectRole')" multiple>
        <el-option v-for="item in allRoles" :label="item.text" :value="item.id" :key="item.id"></el-option>
      </el-select>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="showUpdateDialog = false">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" @click="update" :disabled="pending">{{ $t('common.base.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { t } from '@src/locales'

export default {
  name: 'update-role',
  data() {
    return {
      pending: false,
      showUpdateDialog: false,
      allRoles: [],
      roleIds: [],
      userId: '',
    }
  }, 
  methods: {
    openDialog(allRoles, roles, userId) {
      this.userId = userId;
      this.allRoles = allRoles;
      this.roleIds = roles.map(item=>item.id); 
      this.showUpdateDialog = true;
    },
    async update(){
      try {
        if(!this.roleIds.length) return this.$platform.notification({
          title: t('common.base.tip.modifyFail'),
          message: t('common.validate.requiredRole'),
          type: 'error'
        })
        this.pending = true
        let roleUsers = []
        this.roleIds.forEach(item=>{
          const roleUser = {};
          roleUser.roleId = item;
          roleUser.userId = this.userId;
          roleUsers.push(roleUser);
        })
        const { status, message } = await this.$http.post(`/security/user/setRoleUser?userId=${this.userId}`, roleUsers, true)
        this.pending = false
        if (status !== 0) return this.$platform.notification({
          title: t('common.base.tip.modifyFail'),
          message: message || '',
          type: 'error'
        })
        this.showUpdateDialog = false
        this.$platform.notification({
          title: t('common.base.tip.modifySuccess'),
          type: 'success'
        })
        this.$emit('update')
      } catch (e) {
        console.error(e)
        this.pending = false
      }
    },
    reset(){
      this.roleIds = []
      this.showUpdateDialog = false
    }
  },
}
</script>

<style lang="scss" scoped>
::v-deep.el-dialog__headerbtn {
  top: 0!important;
}
.el-dialog__body {
  .el-select {
    width: 100%;
  }
}
</style>